<template>
  <div class="upImage-container" @click="onSelectImage">
    <el-image style="width: 160px; height: 120px" :src="$route.query.id ? sendImage : coverImage" fit="cover">
      <div slot="error" class="image-slot">
        <i class="el-icon-picture-outline"></i>
      </div>
    </el-image>
    <el-dialog
      :visible.sync="dialogVisible"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="40%"
    >
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="素材库" name="coverLibrary">
          <imageList ref="image-list"></imageList>
        </el-tab-pane>
        <el-tab-pane label="上传图片" name="uploadImage">
          <el-upload
            class="avatar-uploader"
            action
            :headers="uploadHeaders"
            :show-file-list="false"
            :http-request="onUploadImage"
            :on-change="onUploadChange"
            :auto-upload="false"
            ref="upload"
          >
            <img v-if="selectImgUrl" :src="selectImgUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
// 导入接口
import { uploadCoverImage } from '@/api/article'
// 导入自定义模块
import imageList from '@/views/publish/components/imageList'
export default {
  name: 'publishImage',
  data () {
    const user = JSON.parse(window.localStorage.getItem('User'))
    return {
      // 对话框默认关闭状态
      dialogVisible: false,
      // tab选项卡切换样式
      activeName: 'uploadImage',
      // 上传默认无图
      selectImgUrl: '',
      // 封面默认无图
      coverImage: '',
      // 请求头
      uploadHeaders: {
        Authorization: `Bearer ${user.token}`
      }
    }
  },
  methods: {
    // 选择文章封面
    onSelectImage () {
      // 开启对话框
      this.dialogVisible = true
    },
    // 监听input-file的onchange事件
    onUploadChange (file) { // file为选择的文件对象
      // 图片预览
      const blob = window.URL.createObjectURL(file.raw)
      this.selectImgUrl = blob
    },
    // 自定义上传
    async onUploadImage () {
      const file = this.$refs.upload.uploadFiles[0]
      // 执行上传文件的操作
      const fd = new FormData()
      fd.append('image', file.raw)
      // 调用接口,执行上传
      const res = await uploadCoverImage(fd)
      try {
        // 上传成功,关闭对话框
        this.dialogVisible = false
        // 更新封面视图
        this.coverImage = res.data.data.url
        // 向父组件发射上传完的图片素材数据
        this.$emit('receiveImage', res.data.data.url)
      } catch (err) {
        return Promise.reject(err)
      }
    },
    // 开始上传
    onSubmit () {
      // 如果 tab 是上传图片，并且 input-file 有选择的文件，才执行上传图片的操作
      if (this.activeName === 'uploadImage') {
        const file = this.$refs.upload.uploadFiles[0]
        // 如果file对象不存在,提示用户选择图片
        if (!file) {
          this.$message({
            type: 'warning',
            message: '请选择图片'
          })
          return
        }
        this.$refs.upload.submit()
      } else if (this.activeName === 'coverLibrary') {
        const coverVue = this.$refs['image-list']
        const selected = coverVue.selected
        // 如果selectedIndex为空,则提示用户选择封面
        if (selected === null) {
          this.$message('请选择图片封面')
          return false
        }
        // 更新视图
        this.coverImage = coverVue.images[selected].url
        // 关闭对话框
        this.dialogVisible = false
        // 向父组件发射上传完的图片素材数据
        this.$emit('receiveImage', coverVue.images[selected].url)
      }
    }
  },
  props: ['sendImage'],
  components: {
    imageList
  }
}
</script>
<style lang="less">
.upImage-container {
  cursor: pointer;
}
</style>
